<!--
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
-->
<template>
  <el-dialog v-model="props.addVisible" :title="props.type === 'add' ? '新增模板' : '修改模板'" @close="cancel('close')" width="800">
    <div class="add-main">
      <div class="form-data">
        <div>数据模板名称：</div>
        <div class="value-input"><el-input size="small" placeholder="请输入数据模板名称" v-model="templateFormData.name" /></div>
        <div class="row2">
          <div class="item-row">
            <div>业务场景：</div>
            <div class="value-input">
              <el-select size="small" placeholder="请选择业务场景" @change="sceneChange" v-model="templateFormData.scene">
                <el-option v-for="item in scenes" :key="item.name" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>
          </div>
          <div class="item-row">
            <div>要素库类型：</div>
            <div class="value-input">
              <el-select size="small" placeholder="请选择要素库类型" @change="dataBaseChange" v-model="templateFormData.dataBase">
                <el-option v-for="item in dataBases" :key="item.name" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>
          </div>
        </div>
      </div>
      <div class="template-title">数据模板字段选择：</div>
      <div class="template">
        <div class="tips">
          <el-icon size="24" color="yellow"><WarnTriangleFilled /></el-icon
          >注：从要素库类型对应的源表字段中选择所需字段到模板字段；选择源表非必填字段到模板字段时，该表的必填将自动到模板字段中；
        </div>
        <div class="tables">
          <div class="left">
            <div class="title">源表字段</div>
            <div>
              <el-select
                size="small"
                placeholder="表名称"
                style="width: 50%; margin-top: 5px"
                @change="tableChange"
                v-model="templateFormData.tableName"
              >
                <el-option v-for="item in tables" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </div>
            <div class="table">
              <table style="width: 100%" border="1" cellspacing="1">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>字段名称</th>
                    <th>字段类型</th>
                  </tr>
                </thead>
                <tbody v-if="tableFieldList.length > 0">
                  <template v-for="(item, index) in tableFieldList" :key="index">
                    <tr draggable="true" @dragstart="dragStart(item)" @dragend="dragEnd">
                      <td>{{ index + 1 }}</td>
                      <td><span style="color: red" v-if="item.needFlag === '1'">*</span>{{ item.targetField }}</td>
                      <td>{{ item.targetFieldLength }}</td>
                    </tr>
                  </template>
                </tbody>
                <tbody v-else>
                  <tr>
                    <td colspan="4" class="nodata">暂无数据</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <div class="right">
            <div class="title">模板字段</div>
            <div class="btns">
              <el-button size="small" type="primary" link icon="Delete" @click="mappingDelete">删除</el-button>
              <el-button size="small" type="primary" link icon="RefreshLeft" @click="reset">重置</el-button>
            </div>
            <div class="table">
              <table style="width: 100%" border="1" cellspacing="1">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>字段名称</th>
                    <th>所属表</th>
                    <th>字段类型</th>
                  </tr>
                </thead>
                <tbody v-if="templateFieldList.length > 0">
                  <template v-for="(item, index) in templateFieldList" :key="index">
                    <tr @dragover="dragOver" @drop="drop" :class="item.isClick ? 'active' : ''" @click="itemClick(item)">
                      <td>{{ index + 1 }}</td>
                      <td><span style="color: red" v-if="item.needFlag === '1'">*</span>{{ item.targetField }}</td>
                      <td>{{ item.tableName }}</td>
                      <td>{{ item.targetFieldType }}</td>
                    </tr>
                  </template>
                </tbody>
                <tbody v-else>
                  <tr @dragover="dragOver" @drop="drop">
                    <td colspan="4" class="nodata">暂无数据</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button size="small" @click="cancel('close')"> 取消 </el-button>
        <el-button size="small" type="primary" @click="submit"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
  <script name="addtemplate" setup>
import { getScenesList, getDatabaseList, getTableFileds, addTemplate, updateTemplate } from '@/api/dataIntegration/dataTemplate/index';
const props = defineProps(['addVisible', 'rowData', 'type']);
const emit = defineEmits(['handleEvent']);
// 业务场景
const scenes = ref([]);
// 要素库类型
const dataBases = ref([]);
// 源表字段
const tableFieldList = ref([]);
// 模板字段
const templateFieldList = ref([]);
const dragData = ref(null);
// 源表列表
const tables = ref([]);
const templateFormData = ref({
  name: '',
  scene: '',
  dataBase: '',
  tableName: '',
  params: [],
  dataBaseNames: []
});
// 选择场景
const sceneChange = (data, type) => {
  // 场景变化清空模板字段
  if (!type) {
    templateFieldList.value = [];
    tableFieldList.value = [];
    templateFormData.value.tableName = '';
    templateFormData.value.dataBase = '';
  }
  scenes.value.forEach((el) => {
    if (el.id === data) {
      templateFormData.value.sceneName = el.name;
    }
  });
  getDatabaseList({ sceneId: data }).then((res) => {
    if (res) {
      dataBases.value = res?.rows || [];
    }
  });
};
const initData = () => {
  templateFormData.value.id = props?.rowData?.id;
  templateFormData.value.name = props?.rowData?.templateName;
  templateFormData.value.scene = props?.rowData?.businessId;
  templateFormData.value.sceneName = props?.rowData?.businessSceneName;
  const fields = JSON.parse(props?.rowData?.mapFields) || [];
  fields.forEach((el) => {
    templateFieldList.value.push({
      isClick: false,
      ...el
    });
  });
  // 查询对应的要素库
  sceneChange(props?.rowData?.businessId, 'init');
};
// 修改时初始化数据
if (props?.type === 'edit') {
  initData();
}
const dragStart = (event) => {
  dragData.value = event;
};
const dragEnd = (event) => {
  // 恢复拖拽元素的默认样式
  event.target.style.opacity = '1';
};
const dragOver = (event) => {
  event.preventDefault();
};
const drop = (event) => {
  // 阻止浏览器默认操作
  event.preventDefault();
  // 数据处理
  //1、先删除源表数据
  tableFieldList.value = tableFieldList.value.filter((el) => {
    return el.targetField != dragData.value.targetField;
  });
  // 查询要素库名称
  let dataBaseName = '';
  dataBases.value.filter((el) => {
    if (el.id === templateFormData.value.dataBase) {
      dataBaseName = el.name;
    }
  });
  templateFieldList.value.push({
    ...dragData.value,
    isClick: false,
    tableName: templateFormData.value.tableName,
    dataBase: templateFormData.value.dataBase,
    dataBaseName: dataBaseName
  });
};
// 删除
const mappingDelete = () => {
  const selectedData = templateFieldList.value.filter((el) => {
    return el.isClick;
  });
  // 删除模板数据
  templateFieldList.value = templateFieldList.value.filter((el) => {
    return !el.isClick;
  });
  // 回滚数据源表
  selectedData.forEach((el) => {
    if (el.tableName === templateFormData.value.tableName) {
      tableFieldList.value.push(el);
    }
  });
};
// 重置
const reset = () => {
  templateFieldList.value.forEach((el) => {
    if (el.tableName === templateFormData.value.tableName) {
      tableFieldList.value.push(el);
    }
  });
  templateFieldList.value = [];
};
// 右侧表单行点击事件
const itemClick = (data) => {
  templateFieldList.value.forEach((el) => {
    if (el.targetField === data.targetField) {
      el.isClick = !el.isClick;
    }
  });
};
// 取消
const cancel = (type) => {
  emit('handleEvent', { type });
};
// 选择要素库
const dataBaseChange = (data) => {
  tableFieldList.value = [];
  templateFormData.value.tableName = '';
  const chooseDataBase = dataBases.value.filter((el) => {
    return el.id === data;
  });
  const loactions = chooseDataBase[0].storageLocation;
  const locationTmp = loactions.split(',');
  //去除空元素
  tables.value = locationTmp.filter((el) => {
    return el;
  });
};
// 选择源表
const tableChange = (data) => {
  getTableFileds({ tableName: data }).then((res) => {
    if (res) {
      tableFieldList.value = res?.data[0].mapFiledsList || [];
    }
  });
};
// 提交表单
const submit = () => {
  // 数据校验
  if (!templateFormData.value.name) {
    ElMessage({ showClose: true, message: '请填写模板名称！', type: 'error' });
    return;
  }
  if (!templateFormData.value.scene) {
    ElMessage({ showClose: true, message: '请选择场景！', type: 'error' });
    return;
  }
  if (templateFieldList.value.length === 0) {
    ElMessage({ showClose: true, message: '请选择模板字段！', type: 'error' });
    return;
  }
  templateFormData.value.params = [...templateFieldList.value];
  const dataBaseSet = new Set();
  const dataBaseNameSet = new Set();
  templateFieldList.value.forEach((el) => {
    dataBaseSet.add(el.dataBase);
    dataBaseNameSet.add(el.dataBaseName);
  });

  templateFormData.value.dataBaseIds = [...dataBaseSet];
  templateFormData.value.dataBaseNames = [...dataBaseNameSet];
  // 调用提交接口
  console.log(templateFormData.value);
  const params = {};
  params.templateName = templateFormData.value.name;
  params.businessId = templateFormData.value.scene;
  params.businessSceneName = templateFormData.value.sceneName;
  params.databaseType = templateFormData.value.dataBaseNames.toString();
  params.mapFields = JSON.stringify(templateFormData.value.params);

  if (props.type === 'add') {
    addTemplate(params).then((res) => {
      if (res) {
        ElMessage({ showClose: true, message: '新增成功！', type: 'success' });
        cancel('refresh');
      }
    });
  } else {
    params.id = templateFormData.value.id;
    updateTemplate(params).then((res) => {
      if (res) {
        ElMessage({ showClose: true, message: '修改成功！', type: 'success' });
        cancel('refresh');
      }
    });
  }
};
onMounted(() => {
  getScenesList({ pageSize: 1000, pageNum: 1 }).then((res) => {
    if (res) {
      scenes.value = res?.rows || [];
    }
  });
});
</script>
  <style lang="scss" scoped>
.add-main {
  font-size: 12px;
  .form-data {
    .value-input {
      margin-top: 5px;
    }
    .row2 {
      margin-top: 10px;
      display: flex;
      justify-content: space-between;
      .item-row {
        width: 45%;
        .value-input {
          margin-top: 5px;
        }
      }
    }
  }
  .template-title {
    margin-top: 10px;
  }
  .template {
    background: #d9d9d9;
    padding: 10px;
    margin-top: 10px;
    .tips {
      display: flex;
      align-items: center;
    }
    .tables {
      margin-top: 10px;
      display: flex;
      justify-content: space-between;
      .left {
        width: 48%;
        .title {
          font-weight: 600;
        }
        .table {
          width: 100%;
          margin-top: 5px;
          td {
            text-align: center;
          }
          .nodata {
            width: 100%;
            height: 50px;
            line-height: 50px;
            text-align: center;
          }
        }
      }
      .right {
        width: 48%;
        .title {
          font-weight: 600;
        }
        .btns {
          display: flex;
          margin-top: 10px;
        }
        .table {
          width: 100%;
          margin-top: 5px;
          td {
            text-align: center;
          }
          .nodata {
            width: 100%;
            height: 50px;
            line-height: 50px;
            text-align: center;
          }
          .active {
            background: #0879ef4d;
          }
        }
      }
    }
  }
}
</style>